/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.google.common.collect.Lists;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.ExamResult;
import me.zhengjie.modules.system.domain.ExamResultExportRequest;
import me.zhengjie.modules.system.domain.GroupTest;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.ExamInfoService;
import me.zhengjie.modules.system.service.ExamResultService;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.service.dto.ExamInfoDto;
import me.zhengjie.modules.system.service.dto.ExamResultDto;
import me.zhengjie.modules.system.service.dto.ExamResultQueryCriteria;
import me.zhengjie.modules.web.service.IAtmrExamService;
import me.zhengjie.modules.web.service.mybatisplus.IGroupTestPlusService;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author zhaoxiancheng
* @date 2021-11-18
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "测试结果管理管理")
@RequestMapping("/api/examResult")
public class ExamResultController {

    private final ExamResultService examResultService;
    private final WxUserService wxUserService;

    private final ExamInfoService examInfoService;

    @Autowired
    private IGroupTestPlusService  groupTestPlusService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('examResult:list')")
    public void download(HttpServletResponse response, ExamResultQueryCriteria criteria) throws IOException {
        String city = criteria.getCity();
        String mobile = criteria.getMobile();
        List<WxUser> wxUsers = null;
        boolean openId = false;
        if (StringUtils.isNotBlank(city) && StringUtils.isNotBlank(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByParam(city, mobile);
        } else if (StringUtils.isNotBlank(city) && StringUtils.isEmpty(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByCity(city);
        } else if (StringUtils.isNotBlank(mobile) && StringUtils.isEmpty(city)) {
            openId = true;
            wxUsers = wxUserService.findByMoblie(mobile);
        }
        //前端传递了姓名或电话号码参数
        if(openId)
        {
            if (null != wxUsers && wxUsers.size() > 0) {
                criteria.setWxId(wxUsers.get(0).getOpenId());
            }
            else
            {
                criteria.setWxId("-1");
            }
        }
        examResultService.download(examResultService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询测试结果管理")
    @ApiOperation("查询测试结果管理")
    @PreAuthorize("@el.check('examResult:list')")
    public ResponseEntity<Object> query(ExamResultQueryCriteria criteria, Pageable pageable){
        String city = criteria.getCity();
        String mobile = criteria.getMobile();
        List<WxUser> wxUsers = null;
        boolean openId = false;
        if (StringUtils.isNotBlank(city) && StringUtils.isNotBlank(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByParam(city, mobile);
        } else if (StringUtils.isNotBlank(city) && StringUtils.isEmpty(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByCity(city);
        } else if (StringUtils.isNotBlank(mobile) && StringUtils.isEmpty(city)) {
            openId = true;
            wxUsers = wxUserService.findByMoblie(mobile);
        }
        //前端传递了姓名或电话号码参数
        if(openId)
        {
            if (null != wxUsers && wxUsers.size() > 0) {
                criteria.setWxId(wxUsers.get(0).getOpenId());
            }
            else
            {
                criteria.setWxId("-1");
            }
        }
        Map<String,GroupTest> groupTestMap = new HashMap<>();
        Map<String,Object> resultMap = examResultService.queryAll(criteria,pageable);
        for (ExamResultDto obj : (List<ExamResultDto>)resultMap.get("content")) {
            if(obj.getWxId() != null && !"".equals(obj.getWxId()))
            {
                WxUser wu = wxUserService.findByOpenId(obj.getWxId());
                obj.setWxUser(wu);
            }
            if (StringUtils.isNotBlank(obj.getGroupId()) && !"0".equals(obj.getGroupId())){
                GroupTest groupTest = groupTestMap.get(obj.getGroupId());
                if (Objects.isNull(groupTest)){
                    groupTest = groupTestPlusService.getById(obj.getGroupId());
                    groupTestMap.put(obj.getGroupId(),groupTest);
                }
                if (Objects.nonNull(groupTest)){
                    obj.setTestingSource("团测【"+groupTest.getTitle()+"】");
                }else {
                    obj.setTestingSource("团测");
                }
            }else if (StringUtils.isNotBlank(obj.getEntCode())){
                obj.setTestingSource("B端");
            }else {
                obj.setTestingSource("系统");
            }
        }
        groupTestMap.clear();
        return new ResponseEntity<>(resultMap,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增测试结果管理")
    @ApiOperation("新增测试结果管理")
    @PreAuthorize("@el.check('examResult:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody ExamResult resources){
        return new ResponseEntity<>(examResultService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改测试结果管理")
    @ApiOperation("修改测试结果管理")
    @PreAuthorize("@el.check('examResult:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody ExamResult resources){
        examResultService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除测试结果管理")
    @ApiOperation("删除测试结果管理")
    @PreAuthorize("@el.check('examResult:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        examResultService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("导出测试记录")
    @ApiOperation("导出测试记录")
    @PostMapping(value = "/export")
//    @PreAuthorize("@el.check('examResult:list')")
    public void export(HttpServletResponse response, @RequestBody ExamResultExportRequest exportRequest) throws IOException {
        if(CollectionUtils.isEmpty(exportRequest.getPathList())){
            return;
        }
        examResultService.export(exportRequest.getPathList(), response);
    }

    @Log("查询测评得分")
    @ApiOperation("查询测评得分")
    @GetMapping("/test/{id}")
    public ResponseEntity<Object> getTestResult(@PathVariable("id") Integer id) {
        ExamResultDto examResultDto = examResultService.findById(id);
        String examContent = examResultDto.getExamContent();
        String[] examInfos = examContent.split(",");
        List<ExamInfoDto> list = Lists.newArrayList();
        for(String exam : examInfos){
            String[] test = exam.split("_");
            ExamInfoDto examInfoDto = examInfoService.findById(Integer.valueOf(test[0]));
            examInfoDto.setAnswer(test[1]);
            if(StringUtils.isNotBlank(examInfoDto.getChose())){
                String[] options = examInfoDto.getChose().split(";");
                examInfoDto.setOptions(options);
            }
            if(StringUtils.isNotBlank(examInfoDto.getScore())){
                String[] scores = examInfoDto.getScore().split(";");
                examInfoDto.setScores(scores);
            }
            list.add(examInfoDto);
        }

        return new ResponseEntity<>(list,HttpStatus.OK);
    }
}